package com.itheima.sh.consumer.web;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.Map;

/**
 * @Author 96558
 * @Date 2021/1/2 21:17
 * @Version 1.0
 **/
@RestController
@RequestMapping("consumer")
public class ConsumerController {
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    DiscoveryClient discoveryClient;

    @GetMapping("{id}")
    public void queryById(@PathVariable("id") String username){

        //String url = "http://localhost:8081/user/"+username;
        //Map userMap = restTemplate.getForObject(url, Map.class);
        //基于Eureka  调用
        List<ServiceInstance> instances = discoveryClient.getInstances("USER-SERVICE");
        ServiceInstance serviceInstance = instances.get(0);
        String host = serviceInstance.getHost();
        int port = serviceInstance.getPort();

        String url = serviceInstance.getUri().toString();
        System.out.println("url"+url);

        String urlconn = "http://"+host+":"+port+"/user/"+username;
        Map userMap = restTemplate.getForObject(url, Map.class);
        System.out.println(userMap);
    }
}
